package org.pausd.gunn.compsci;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.io.InputStreamReader;
/**
 * The client-side proxy for a game object, but treat it as any game. It will forward
 * messages which will be received and parsed by NetworkPlayer, which will call the appropriate
 * methods on the LocalGame object.
 * @author CodyS
 *
 */
public class NetworkGame extends Game implements Messager {
	private Socket connect;
	private BufferedReader reader;
	private PrintWriter writer;
	private Player p;
	public NetworkGame(Socket s) {
		connect = s;
		try {
			reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
			writer = new PrintWriter(s.getOutputStream());
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		
	}
	@Override
	/**
	 * Tell the server to add something to the counter.
	 */
	public void addToCounter(int add) {
		send("add "+add);
	}

	@Override
	/**
	 * Tell the server tha this player is ready.
	 */
	public void playerReady(Player p) {
		send("ready");
	}

	@Override
	/**
	 * Call this with the LocalPlayer after it has been instantiated so that it can receive
	 * messages from this class.
	 */
	public void addPlayer(Player p) {
		this.p = p;
		Thread t = new Thread(new NetworkListener(this,reader));
		t.start();
	}

	@Override
	public void removePlayer(Player p) {
		p.leave();
	}
	@Override
	/**
	 * Sends a message to the server, which will be received by NetworkPlayer
	 */
	public void send(String message) {
		writer.println(message);
		writer.flush();
	}
	/**
	 * Parses a message and calls the appropriate method on the Player
	 */
	public void receive(String message) {
		String[] info = message.split(" ");
		if(info[0].equals("start")) {
			p.started();
		}
		else if(info[0].equals("counter")) {
			p.counter(Integer.parseInt(info[1]));
		}
		else if(info[0].equals("ready")) {
			p.ready();
		}
		else if(info[0].equals("sorry")) {
			p.leave();
		}
		else if(info[0].equals("turn")) {
			p.doTurn();
		}
	}
}
